package com.celesea.configuration.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


public class NetworkHelper {

    public static final String SHORT_IP_FORMAT = "%s.%s";
    private static final Logger LOGGER = LoggerFactory.getLogger(NetworkHelper.class);

    /**
     * 多IP处理，可以得到最终ip
     *
     * @return
     */
    public static IpAddress getIp() {
        List<InetAddress> localIPs = new ArrayList<>();// 本地IP，如果没有配置外网IP则返回它
        List<InetAddress> netIPs = new ArrayList<>();// 外网IP
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            //            boolean finded = false;// 是否找到外网IP
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    ip = address.nextElement();
                    if(!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1){

                    }
                    InetAddress address1 = (InetAddress)ip;
                    if(address1 instanceof Inet4Address && !address1.isLoopbackAddress()) {
//                        System.out.println("Found non-loopback interface: " + ni.getDisplayName()+":"+address1.getHostAddress());
                    }
                    boolean has = !ni.isLoopback() && !ni.isPointToPoint() && !ni.isVirtual();
                    has = has && !(ni.getName().contains("vmnet") || ni.getName().contains("utun") || ni.getName().contains(
                            "vboxnet"));
                    if (ni.isUp() && has) {
                        if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                            //                            System.out.println(ni.getName() + ";" + ip.getHostAddress() + ";ip.isSiteLocalAddress()=" + ip.isSiteLocalAddress() + ";ip.isLoopbackAddress()=" + ip.isLoopbackAddress());
                            if (ip.isSiteLocalAddress()) {// 内网IP
                                localIPs.add(ip);
                            } else {//外网IP
                                netIPs.add(ip);
                            }
                        }
                    }
                }

            }
        } catch (SocketException e) {
            LOGGER.error("", e);
        }

        return new IpAddress(localIPs, netIPs);
    }

    public static class IpAddress {
        private static final Logger logger = LoggerFactory.getLogger(IpAddress.class);
        final static String DefaultIP = "127.0.0.1";
        public final List<InetAddress> localIPs;
        public final List<InetAddress> netIPs;


        public IpAddress(List<InetAddress> localIPs, List<InetAddress> netIPs) {
            this.localIPs = localIPs;
            this.netIPs = netIPs;
        }

        public String getIP() {
            if (netIPs != null && netIPs.size() > 0) return netIPs.get(0).getHostAddress();
            if (localIPs == null || localIPs.size() == 0) return DefaultIP;
            return localIPs.get(0).getHostAddress();
        }

        public InetAddress getLocalInetAddress() {
            if (localIPs != null && localIPs.size() > 0) return localIPs.get(0);
            if (netIPs != null && netIPs.size() > 0) return netIPs.get(0);
            return getDefaultInetAddress();
        }

        public InetAddress getInetAddress() {
            if (netIPs != null && netIPs.size() > 0) return netIPs.get(0);
            if (localIPs == null || localIPs.size() == 0) return getDefaultInetAddress();
            return localIPs.get(0);
        }

        private InetAddress getDefaultInetAddress() {
            InetAddress inetAddress = null;
            try {
                inetAddress = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                logger.error("", e);
            }
            return inetAddress;
        }


        @Override
        public String toString() {
            return "IpAddress{" +
                    "localIPs=" + localIPs +
                    ", netIPs=" + netIPs +
                    '}';
        }
    }

    public static String getShortIP(String ip) {
        String[] sip = ip.split("\\.");

        if (sip.length >= 4) {
            return String.format(SHORT_IP_FORMAT, sip[2], sip[3]);
        }
        return ip;
    }

    public static void main(String[] args) throws UnknownHostException {
        IpAddress ipAddress = getIp();
        System.out.println(ipAddress);
        System.out.println(ipAddress.getIP());
        String ip = InetAddress.getLocalHost().getHostAddress();

        System.out.println(ip);
        System.out.println();
        System.out.println(getShortIP(ip));

        System.out.println("------");
        System.out.println(ip);

    }
}
